/**
 * 
 */
package will.icecoffe.core;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;

import will.icecoffe.utils.Page;

/**
 * @author will
 * @param <T>
 *
 */
@Component("basicQBCFinder")
public class BasicQBCFinder<T> extends Finder<T> {

	@Override
	public List<T> find(final Object... args) throws DataAccessException {
		
		List<T> list = null;
		list = dao.getHibernateTemplate().executeFind(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				Criteria c = session.createCriteria((Class) args[0]);
				Object[] params = new Object[args.length - 1];
				params = Arrays.copyOfRange(args, 1, args.length);
				for(Object o : params) {
					c.add((Criterion) o);
				}
				return c.list();
			}
		});
		
		return list;
	}

	@Override
	public Page<T> find(final int page, final int rows, final Object... args)
			throws DataAccessException {
		Page<T> list = null;
		list = (Page<T>) dao.getHibernateTemplate().executeFind(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				Criteria c = session.createCriteria((Class) args[0]);
				Object[] params = new Object[args.length - 1];
				params = Arrays.copyOfRange(args, 1, args.length);
				for(Object o : params) {
					c.add((Criterion) o);
				}
				c.setFirstResult((page - 1) * rows);
				c.setMaxResults(rows);
				return c.list();
			}
		});
		
		return list;
	}

}
